package com.szyt.basicframe.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.szyt.basicframe.pojo.bo.LoginUser;
import com.szyt.basicframe.util.JwtUtil;
import com.szyt.basicframe.util.LoginUtil;
import com.szyt.basicframe.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 请求头获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            // 放行
            filterChain.doFilter(request,response);
            return;
        }

        // 解析token
        String userId;
        try {
            userId = jwtUtil.getUserIdFromToken(token);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // redis获取用户信息
        String redisKey = LoginUtil.getUserCacheKey(userId);
        LoginUser loginUser = redisUtil.get(redisKey, LoginUser.class);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }

        // 存入securitycontextholder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request,response);
    }
}
